package com.wenbei.controller;

import com.wenbei.common.DistributedRedisLock;
import com.wenbei.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 测试controller
 * @author 北哥 公众号：BiggerBoy
 * @date 2022-9-8 17:39:31
 */
@RestController
public class TestController {
    @Autowired
    JedisPool jedisPool;
    String lua = "local c_s = redis.call('get', KEYS[1])\n" +
            "if not c_s or tonumber(c_s) < tonumber(KEYS[2]) then\n" +
            "return 0\n" +
            "end\n" +
            "redis.call('decrby',KEYS[1], KEYS[2])\n" +
            "return 1";
    String lua_sha1 = "";

//    @PostConstruct
//    public void init() {
//        try (Jedis jedis = jedisPool.getResource()) {
//            String scriptLoad = jedis.scriptLoad(lua);
//            lua_sha1 = scriptLoad;
//        }
//    }

    //p:1:stock
    @RequestMapping(value = "/buy")
    public Long buy(String key, String buyNum) {
        try (Jedis jedis = jedisPool.getResource()) {
            Object scriptLoad = jedis.evalsha(lua_sha1, 2, key, buyNum);
            return (Long) scriptLoad;
        }
    }

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    DistributedRedisLock distributedRedisLock;


    @RequestMapping(value = "/test")
    public String test(User user, HttpServletRequest httpServletRequest) {
//        String key = "test:bigbigbgiggigigigiigiggigigigi";
//        for (int i = 0; i < 126; i++) {
//            redisTemplate.opsForHash().put(key, i + "-000000", "xacxedx00xhumbnailqx00~x9x");
//        }
//
//        redisTemplate.unlink("");
//        System.out.println(user);
//        System.out.println(redisTemplate.opsForValue().get("name"));
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        distributedRedisLock.lock("");
        return "test";
    }

    //测试文件上传
    @RequestMapping(value = "/update")
    public String update(User user, HttpServletRequest httpServletRequest) {
        MultipartFile file = user.getFile();
        System.out.println(file.getName());
        try {
            byte[] bytes = file.getBytes();
            FileOutputStream fos = new FileOutputStream(new File("D:/" + file.getOriginalFilename()));
            fos.write(bytes);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "test";
    }
}
